package com.jrapider.compent.dict;

import com.alibaba.fastjson.JSON;
import com.jrapider.CommonConstants;
import com.jrapider.om.PageInfo;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @Auther: hxs
 * @Date: 2018/12/31
 * @Description:
 */
@Component("constant")
@Log4j2
public class ComConstantProvider implements IDictProvider {
    private static Map<String, List<DictData>> data = new HashMap<>();

    static {
        Field[] fields = CommonConstants.class.getFields();
        for (Field field : fields) {
            String name = field.getName();
            if (!name.startsWith("DICT")|| name.endsWith("CN")) {
                continue;
            }
            String[] nameArrays = name.split("_");
            if (nameArrays.length != 3) {
                continue;
            }
            String type = nameArrays[1];
            List<DictData> dictDatas = data.get(type);
            if (dictDatas == null) {
                dictDatas = new ArrayList<>();
                data.put(type, dictDatas);
            }
            try {
                Object value = field.get(null);
                Field cnField = CommonConstants.class.getField(field.getName() + "_CN");
                Object note = cnField.get(null);
                dictDatas.add(new DictData() {{
                    setCode(type);
                    setValue(value.toString());
                    setNote(note == null ? "" : note.toString());
                }});
            } catch (IllegalAccessException e) {
                log.error(e.getMessage(), e);
            } catch (NoSuchFieldException e) {
                log.error(e.getMessage());
            }
        }
        log.info("公共字典=====>");
        for (String key : data.keySet()) {
            log.info(key);
            log.info(JSON.toJSONString(data.get(key)));
        }
        log.info("公共字典=====<");
    }


    @Override
    public Set<String> supportCodes() {
        return data.keySet();
    }

    @Override
    public List<DictData> getDict(String code) {
        return data.get(code);
    }

    @Override
    public List<DictData> getDict(String code, String filter, PageInfo pageInfo) {
        return data.get(code);
    }
}
